<template>
    <SysDialog :title="dialog.title" :visible="dialog.visible" :width="dialog.width" :height="dialog.height"
    @onClose="onClose" @onConfirm="commit">
        <template v-slot:content>
            <el-form :model="addModel" ref="addFormRef" :rules="rules" label-width="80px" :inline="false" size="default">
                <el-form-item prop="categoryName" label="分类名称">
                    <el-input v-model="addModel.categoryName"></el-input>
                </el-form-item>
                <el-form-item prop="orderId" label="序号">
                    <el-input v-model="addModel.category"></el-input>
                </el-form-item>
            </el-form>
            
        </template>
    </SysDialog>
</template>

<script setup lang="ts">
import SysDialog from '@/components/SysDialog.vue';
import useDialog from '@/tools/useDialog';
import { CategoryModel} from '@/api/category/CategoryModel'
import { reactive,ref,nextTick } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { addCategoryApi,editCategoryApi} from '@/api/category/index';
import { EditType } from '@/type/BaseType';
//表单的ref属性
const addFormRef = ref<FormInstance>();
//弹框属性
const { dialog,onClose,onConfirm,onShow} = useDialog()
//显示弹框
const show = (type:string,row?:CategoryModel)=>{
    dialog.title = '新增'
    dialog.height = 80;
    onShow();
    //编辑时显示出数据
    if(row && type == EditType.EDIT){
        dialog.title = '编辑'
        nextTick(()=>{
            Object.assign(addModel,row)
        })
    }
    //设置编辑的属性：0：新增、1：编辑
    addModel.type = type;
    //清空表单
    addFormRef.value?.resetFields()
}
//将方法显露出去给父组件调用
defineExpose({
    show
})
//表单绑定的对象
const addModel = reactive<CategoryModel>({
    type:'',
    categoryId:'',
    categoryName:'',
    category:'',
})
//表单验证规则
const rules = reactive({
    categoryName:[{
        required:true,
        message:"请填写分类名",
        trigger:"blur",
    },
    ],
});
//注册事件
const emists = defineEmits(['onFresh'])
//表单提交
const commit = ()=>{
    addFormRef.value?.validate(async(valid)=>{
        if(valid){
            let result = null;
            if(addModel.type == EditType.ADD){
                result = await addCategoryApi(addModel)
            }else{
                result = await editCategoryApi(addModel)
            }
            if(result && result.code == 200){
                ElMessage.success(result.msg)
                //刷新表格
                emists('onFresh')
                onClose()
            }else if(result && result.code == 1){
                ElMessage.error(result.msg)
                //刷新表格
                emists('onFresh')
            }
        }
    })
}
</script>

<style scoped>

</style>